package com.lsh.ofc.provider.rest.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lsh.base.common.model.CommonResult;
import com.lsh.ofc.core.entity.OfcSoHead;
import com.lsh.ofc.core.service.OfcSoService;
import com.lsh.ofc.provider.common.util.Pageable;
import com.lsh.ofc.provider.rest.service.SaleOrderRestService;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import java.util.List;

@Path("sale-orders")
@Service(protocol = "rest", timeout = 30000)
public class SaleOrderRestServiceImpl implements SaleOrderRestService {

    @Resource
    private OfcSoService ofcSoService;

    @GET
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public CommonResult<Pageable<OfcSoHead>> query(@Context UriInfo uriInfo,
                                                   @DefaultValue("1") @QueryParam("page") long page,
                                                   @DefaultValue("20") @QueryParam("page-limit") long limit) {
        MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
        List<OfcSoHead> entities = ofcSoService.findList(filter(queryParameters), detailsRequired(queryParameters));
        return CommonResult.success(new Pageable<>(entities, page));
    }

    private boolean detailsRequired(MultivaluedMap<String, String> queryParameters) {
        String detailsRequired = queryParameters.getFirst("details-required");
        return "true".equalsIgnoreCase(detailsRequired);
    }

    private OfcSoHead filter(MultivaluedMap<String, String> queryParameters) {
        OfcSoHead filter = new OfcSoHead();
        String orderId = queryParameters.getFirst("order-id");
        if (orderId != null) {
            filter.setOrderCode(Long.valueOf(orderId));
        }
        return filter;
    }
}
